<?php
namespace app\common\library;


use fast\Http;
use think\Cache;

/**
 * php-demo，仅供参考
 */
class Openapi
{
    // URI前缀
    protected static $base_uri = "https://xlapi.51xinlong.com";

    // key
    protected static $app_id = "630768490265780224";

    // 秘钥
    protected static $app_secret = "SS6RX7d72sCGr8Yi";


    // 集团id
    protected static $companyid = "631129677214515200";

    // 主体账户
    protected static $main_account = "15761916970096";
	
	
	/**
	 * POST请求接口方法
	 * @param string $method
	 * @param array $params
	 * @return string
	 * @throws \Exception
	 */
    public static function requestPost(string $method,array $params = []) : string
    {
        $uri = self::$base_uri."/openapi?service={$method}";
        $header = [
            "Authorization:". "Bearer ".self::getToken(),
            "traceID:". uniqid(),
            "companyid:". self::$companyid,
            "mainAccount:".self::$main_account
        ];
        $postUrl = $uri;
        $curlPost = [
            'timestamp' => time() * 1000,
            'appKey' =>self::$app_id,
            'version' => "V1.1.0",
            'requestBody' => self::getEncryptionData($params),
            'appSecret' => self::$app_secret
        ];
        $curlPost['signature'] = self::getKey($curlPost);
        unset($curlPost['appSecret']);
	    return Http::post($postUrl,$curlPost,[
		    CURLOPT_HTTPHEADER=>$header
	    ]);
	
    }
	
	public static function getToken()
	{
		return Cache::remember('openapi_access_token', function () {
			$url = self::$base_uri."/jwt/auth/openapi?appid=".self::$app_id."&secret=".self::$app_secret;
			//获取接口调用凭据
			$result = Http::get($url);
			$result = json_decode($result);
		
			if (empty($result->access_token)) {
				throw new \Exception("获取token失败");
			}
			return $result->access_token;
		}, 7200);
	}

    /**
     * 获取签名
     * @param array $params
     * @return string
     */
	public static function getKey(array $params) : string
    {
        ksort($params, SORT_NATURAL | SORT_FLAG_CASE);//排序不区分大小写
        $str = '';
        foreach ($params as $k => $v) {
            if ($k == 'signature' || $k == 'requestBody') continue;
            $str .= $k . $v;
        }
        $str = 'key' . $str . 'secret';
        // 对该字符串进行 SHA1 运算,得到一个十六进制的数
	    return strtoupper(sha1($str));
    }

    /**
     * 获取加密数据
     * @param array $params
     * @return string
     */
	public static function getEncryptionData(array $params) : string
    {
        $requestBody = $params;
        $key = self::$app_secret;
        $body = json_encode($requestBody);
        $l = strlen($key);
        if ($l < 16)
            $key = str_repeat($key, ceil(16 / $l));
        if ($m = strlen($body) % 16)
            $body .= str_repeat("\x00", 16 - $m);

        return  base64_encode(openssl_encrypt($body, "AES-128-CBC", $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING, $key));
    }

}

//$req = new \demo\OpenApi();
//$params = [
//    "uid" => "XXXXXXXXXXX"
//];
//$result = $req->requestPost("getBalance",$params);
//var_dump($result);
